package org.linlinjava.litemall.wx.web;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCompanyInfo;
import org.linlinjava.litemall.db.service.LitemallCompanyInfoService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/wx/companyInfo")
@Validated
public class LitemallCompanyInfoController {

    @Autowired
    private LitemallCompanyInfoService litemallCompanyInfoService;


    @CacheEvict(value = "CompanyInfo", allEntries = true)
    @PostMapping("/save")
    public Object save(@RequestBody LitemallCompanyInfo companyInfo) {
        // 先查询数据库中是否已存在该公司信息
        LitemallCompanyInfo existingInfo = litemallCompanyInfoService.findByUserId(companyInfo.getUserId());

        boolean result;
        if (existingInfo == null) {
            // 不存在，执行插入操作
            result = litemallCompanyInfoService.addCompanyInfo(companyInfo);
        } else {
            // 已存在，执行更新操作
            companyInfo.setId(existingInfo.getId()); // 设置ID以确保更新正确的记录
            result = litemallCompanyInfoService.updateCompanyInfo(companyInfo);
        }
        if (result) {
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.fail();
        }
    }

    @Cacheable(value = "CompanyInfo", key = "#userId != null ? #userId : #loginUserId")
    @GetMapping("/getCompanyInfo")
    public Object getCompanyInfo(@RequestParam(required = false) Integer loginUserId, @LoginUser Integer userId) {
        Integer userInfoId = userId != null ? userId : loginUserId;
        LitemallCompanyInfo existingInfo = litemallCompanyInfoService.findByUserId(userInfoId);
        return ResponseUtil.ok(existingInfo);
    }
}
